package com.wu.ssm.spring.mvc.impl;

//import com.wu.ssm.spring.ioc.ControllerHelper;

import com.wu.ssm.spring.ioc.ActionHelper;
import com.wu.ssm.spring.mvc.Handler;
import com.wu.ssm.spring.mvc.HandlerMapping;
import com.wu.ssm.spring.mvc.RequestMappingHandler;
import com.wu.ssm.spring.mvc.Requester;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * Created by wzf on 2018/12/14/014.
 */
public class DefaultHandlerMapping implements HandlerMapping {

    /**
     * 用于缓存 Handler 实例
     */
    private static final Map<String, RequestMappingHandler> cache = new ConcurrentHashMap<>();


//    @Override
//    public Handler getHandler(String currentRequestMethod, String currentRequestPath) {
//        // 若缓存中存在对应的实例，则返回该实例
//        String cacheKey = currentRequestMethod + ":" + currentRequestPath;
//        if(cache.containsKey(cacheKey)){
//            //return cache.get(cacheKey);
//        }
////        RequestMappingHandler requestMappingHandler = ControllerHelper.getHander(currentRequestMethod, currentRequestPath);
////        if (requestMappingHandler != null) {
////            cache.put(cacheKey, requestMappingHandler);
////            //return requestMappingHandler;
////        }
//        return null;
//    }

    @Override
    public Handler getHandler(String currentRequestMethod, String currentRequestPath) {
        // 定义一个 Handler
        Handler handler = null;
        // 获取并遍历 Action 映射
        Map<Requester, Handler> actionMap = ActionHelper.getActionMap();
        for (Map.Entry<Requester, Handler> actionEntry : actionMap.entrySet()) {
            // 从 Requester 中获取 Request 相关属性
            Requester requester = actionEntry.getKey();
            String requestMethod = requester.getRequestMethod();
            // 正则表达式
            String requestPath = requester.getRequestPath();
            // 获取请求路径匹配器（使用正则表达式匹配请求路径并从中获取相应的请求参数）
            Matcher requestPathMatcher = Pattern.compile(requestPath).matcher(currentRequestPath);
            // 判断请求方法与请求路径是否同时匹配
            if (requestMethod.equalsIgnoreCase(currentRequestMethod) && requestPathMatcher.matches()) {
                // 获取 Handler 及其相关属性
                handler = actionEntry.getValue();
                // 设置请求路径匹配器
                if (handler != null) {
                    handler.setRequestPathMatcher(requestPathMatcher);
                }
                // 若成功匹配，则终止循环
                break;
            }
        }
        // 返回该 Handler
        return handler;
    }
}
